import { computed } from 'vue'
import { mapState, useStore, mapGetters, createNamespacedHelpers } from 'vuex'

function userMap (mapper, mapperFn) {
  // 拿到store独享
  const store = useStore()

  // 获取到对应的对象的functions:[name:function,age:function]
  const storeStateFns = mapperFn(mapper)

  // 对数据进行转换
  const storeState = {}
  Object.keys(storeStateFns).forEach(fnkey => {
    const fn = storeStateFns[fnkey].bind({ $store: store })
    storeState[fnkey] = computed(fn)
  })

  return storeState
}

export function userState (mapper, moduleName) {
  let mapperFn = mapState
  if (typeof moduleName === 'string' && moduleName.length > 0) {
    mapperFn = createNamespacedHelpers(moduleName).mapState
  }
  console.log(moduleName, mapperFn)
  return userMap(mapper, mapperFn)
}

export function userGetters (mapper, moduleName) {
  let mapperFn = mapGetters
  if (typeof moduleName === 'string' && moduleName.length > 0) {
    mapperFn = createNamespacedHelpers(moduleName).mapGetters
  }
  return userMap(mapper, mapperFn)
}

// 使用  import {userState} from '../hooks/useVuex'

// 方法一：不改名
// setup(){
//     const storeState = userState(['name','age','height'])
//     return {
//         ...storeState
//     }
// }

// 方法二：改名
// setup(){
//     const storeState = userState({
// a:state=>state.name,
// b:state=>state.age,
// c:state=>state.height
// })
//     return {
//         ...storeState
//     }
// }

// 子模块使用,子模块必须加   namespaced:true
// 使用  import {userState} from '../hooks/useVuex'

// 方法一：不改名,
// setup(){
//     const storeState = userState(['name','age','height'],'cart')
//     return {
//         ...storeState
//     }
// }
